import Koa from 'koa';
import bodyparser from 'koa-bodyparser';
import logger from 'koa-logger';
import json from 'koa-json';
import views from 'koa-views';
import koaStatic from 'koa-static';
import { rootPath } from '../config';

export default function(app: Koa) {
  app.use(
    bodyparser({
      enableTypes: ['json', 'form', 'text'],
    }),
  );
  app.use(json());
  app.use(logger());
  // static
  app.use(koaStatic(rootPath('public')));
  // views
  app.use(
    views(rootPath('views'), {
      extension: 'pug',
    }),
  );

  // logger
  app.use(async (ctx, next) => {
    const start: Date = new Date();
    await next();
    const ms: number = (new Date() as any) - (start as any);
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
  });
  // error-handling
  app.on('error', (err, ctx) => {
    console.error('server error', err, ctx);
  });
}

